﻿CREATE PROCEDURE [dbo].[ListTimeEntriesByCategory]
@CategoryID INT, @ProjectID INT=NULL
AS
SELECT u.UserName, 
		u.UserID, 
		t.MinEntryDate,
		t.MaxEntryDate,
		SUM(e.Duration) AS Duration
FROM EntryLog e
	INNER JOIN Users u ON e.UserID = u.UserID
	INNER JOIN	(	SELECT UserID, 
							MIN(EntryDate) AS MinEntryDate, 
							MAX(EntryDate) AS MaxEntryDate 
					FROM EntryLog 
					GROUP BY UserID ) AS t 
	    ON t.UserID = e.UserID
WHERE e.CategoryID = @CategoryID
	AND e.ProjectID = COALESCE(@ProjectID, e.ProjectID)
GROUP BY u.UserName, 
		u.UserID, 
		t.MinEntryDate, 
		t.MaxEntryDate

